package com.kea.firsthorse.server;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.kea.firsthorse.server.MysqlController;
import com.kea.firsthorse.shared.Horse;
import com.kea.firsthorse.shared.HorsePolicy;
import com.kea.firsthorse.shared.Terms;
import com.kea.firsthorse.shared.User;

public class DataController implements DataControllerIface {
	MysqlControlIface databaseControllInstance = new MysqlController();

	// TODO: lukke alle resultsæt pænt...
	/**
	 * Tager et brugerID og et passwordhash og ser om parret matcher Hashet skal
	 * foregå på brugersiden for at undgå MiM angreb
	 * 
	 * @see com.kea.firsthorse.server.DataControllerIface#validate_user(int,
	 *      java.lang.String)
	 */
	@Override
	public boolean validate_user(int brugerID, String passwordHash) {
		boolean resultat = false;
		try {
			System.out.println("-----------------DB--------------------------");
			databaseControllInstance.connect();
			ResultSet userPWresultSet = databaseControllInstance.getUserPWHash(brugerID);
			if (userPWresultSet == null || !userPWresultSet.first()) {
				System.out
						.println("*****************************bruger ikke fundet********");
			} else {
				System.out.println("Rows returned apparently....");
				String hash = userPWresultSet.getString("password");
				System.out.println("DB-Hash = " + hash + ", Supplied-Hash= "
						+ passwordHash);
				// String hash = n.getUserPWHash(id).getString("password");
				System.out
						.println("-----------------DB2--------------------------");
				resultat = (hash.equals(passwordHash));
			}
		} catch (Exception e) {
			System.err.println("Error message: " + e.getMessage());
			System.err.println("Error number: "
					+ ((SQLException) e).getErrorCode());
		}
		databaseControllInstance.disconnect();
		System.out.println("UserPWMatched = " + resultat);
		return resultat;
	}

	/**
	 * Henter data og opretter et brugerobjekt med alle sammenk�dede data ud fra
	 * et id.
	 * 
	 * @see com.kea.firsthorse.server.DataControllerIface#getUserData(int)
	 */
	@Override
	public User getUserData(int user_id) {
		User User = null;

		try {
			databaseControllInstance.connect();
			ResultSet f = databaseControllInstance.getUserbyID(user_id);
			if (f == null || !f.first()) {
				System.out
						.println("No user resultset returned, PANIC! Ninjas are approaching'");
				// intet resultset... - kan være opdateret fra anden kilde under
				// kørsel.
			} else {
				System.out.println("User found");
				User = this.extractUinfo(f);
				System.out.println("username is : " + User.getFornavn());
				ResultSet ups = databaseControllInstance.getPoliciesbyUserID(User.getUser_id());
				if (ups == null || !ups.first()) { // sætter curser på 1 element
													// hvis fundet....
					// ingen policer
					System.out.println("Denne bruger har ingen policer");
				} else {
					System.out
							.println("Denne bruger har en eller flere policer");
					// fundne police(r)
					ups.beforeFirst(); // flyt RS curser til starten af sættet
					while (ups.next()) {
						HorsePolicy hpt = this.extractPinfo(ups);
						User.addHorsePolicy(hpt);
						
						ResultSet tms = databaseControllInstance.getTermsbyPolicyID(hpt.getPolicy_id());
						
						if (tms == null || !tms.first()){
							System.out.println("No terms for policy found -- argh");
						}else{
							System.out.println("Adding terms");
							Terms t = this.extractTinfo(tms);
							hpt.setTerms(t);
						}
						

						ResultSet hrs = databaseControllInstance
								.getHorsebyPolicyID(hpt.getPolicy_id());
						if (hrs == null || !hrs.first()) {
							System.out
									.println("No horse found, probably eaten by a grue...");
						} else {
							System.out.println("Extracting horse info...");
							Horse nh = this.extractHinfo(hrs);
							nh.setHorsepolicy(hpt);
							System.out.println("Adding horse : "
									+ nh.getHorse_name());
							User.addHorse(nh);
						}
						System.out.println("HorsePolicyID = "
								+ hpt.getPolicy_id());
					}
				}
			}
		}

		catch (Exception e) {
			System.err.println("Error message: " + e.getMessage());
			System.err.println("Error number: "
					+ ((SQLException) e).getErrorCode());

		}
		databaseControllInstance.disconnect();
		return User;
	}

	/**
	 * Parser et resultset til en brugertype
	 * 
	 * @see com.kea.firsthorse.server.DataControllerIface#extractUinfo(java.sql.ResultSet)
	 */
	@Override
	public User extractUinfo(ResultSet userResultSet) {
		User userInstance = new User();
		try {
			userInstance.setFornavn(userResultSet.getString("fornavn"));
			userInstance.setEfternavn(userResultSet.getString("efternavn"));
			userInstance.setAdresse(userResultSet.getString("adresse"));
			userInstance.setBy(userResultSet.getString("by"));
			userInstance.setCvr(Integer.parseInt(userResultSet.getString("cvr")));
			userInstance.setEmail(userResultSet.getString("email"));
			userInstance.setFax(userResultSet.getString("by"));
			userInstance.setFirmanavn(userResultSet.getString("by"));
			userInstance.setLand(userResultSet.getString("land"));
			// U.setLastDate(r.getString("lastdate")); TODO:-> split ud i
			// logtabel.
			userInstance.setLokal(userResultSet.getString("lokal"));
			userInstance.setPostnr(Integer.parseInt(userResultSet.getString("postnr")));
			userInstance.setTelefon(userResultSet.getString("telefon"));
			userInstance.setUser_id(Integer.parseInt(userResultSet.getString("user_id")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return userInstance;
	}

	/**
	 * parser et ResultSet til en hestetype
	 * 
	 * @see com.kea.firsthorse.server.DataControllerIface#extractHinfo(java.sql.ResultSet)
	 */
	@Override
	public Horse extractHinfo(ResultSet horseResultSet) {
		Horse horseInstance = new Horse();
		try {
			printtabledata(horseResultSet);
			horseInstance.setAndet(Integer.parseInt(horseResultSet.getString("andet")));
			horseInstance.setBdate(horseResultSet.getString("b_date"));
			horseInstance.setHorse_name(horseResultSet.getString("horse_name"));
			horseInstance.setRace(horseResultSet.getString("race"));
			horseInstance.setRidning(Integer.parseInt(horseResultSet.getString("Ridning")));
			horseInstance.setStambogsnr(horseResultSet.getString("stambogsnr"));
			horseInstance.setTravGalop(Integer.parseInt(horseResultSet.getString("Travgallop")));

		} catch (Exception e) {
			System.err.println("Error message: " + e.getMessage());
			System.err.println("Error number: "
					+ ((SQLException) e).getErrorCode());
		}
		return horseInstance;
	}
	/**
	 * @author Stephan Marc Hansen
	 */	
	
	
	public Terms extractTinfo(ResultSet termsResultSet) {
		Terms termsInstance = new Terms();
		try {
			printtabledata(termsResultSet);
			termsInstance.setTerm_id(Integer.parseInt(termsResultSet.getString("term_id")));
			termsInstance.setTerms(termsResultSet.getString("betingelser"));
			termsInstance.setSkader(termsResultSet.getString("skader"));
			termsInstance.setStempel(termsResultSet.getString("stempel"));
		} catch (Exception e) {
			System.err.println("Error message: " + e.getMessage());
			System.err.println("Error number: "
					+ ((SQLException) e).getErrorCode());
		}
		return termsInstance;
	}
	

	/**
	 * Parser et policyobjekt ud fra et resultset.
	 * 
	 * @see com.kea.firsthorse.server.DataControllerIface#extractPinfo(java.sql.ResultSet)
	 */
	@Override
	public HorsePolicy extractPinfo(ResultSet horsepolicyResultSet) {
		HorsePolicy horsePolicyInstance = new HorsePolicy();
		try {
			/*
			 * System.out.println("Wakka wakka this time for africa...");
			 * System.out.println(rp.toString()); //hvordan ser tabellen ud ?
			 * printtabledata(rp)
			 */
			horsePolicyInstance.setPolicy_id(Integer.parseInt(horsepolicyResultSet.getString("policy_id")));
			// HP.setAmount(Integer.parseInt(rp.getString("amount")));TODO: hvad
			// er det ?
			horsePolicyInstance.setLivsforsikring(Integer.parseInt(horsepolicyResultSet
					.getString("livsforsikring")) > 0);
			horsePolicyInstance.setPersonskade(Integer.parseInt(horsepolicyResultSet.getString("personskade")) > 0);
			horsePolicyInstance.setSelvrisiko_kolik(Integer.parseInt(horsepolicyResultSet
					.getString("selvrisko_kolik")));
			horsePolicyInstance.setSelvrisiko_sygeforsikring(Integer.parseInt(horsepolicyResultSet
					.getString("selvrisiko_sygeforsikring")));
			horsePolicyInstance.setTime(horsepolicyResultSet.getString("effecive_date"));
			horsePolicyInstance.setTingskade(Integer.parseInt(horsepolicyResultSet.getString("tingskade")) > 0);
			horsePolicyInstance.setU_anvendelighedstab(Integer.parseInt(horsepolicyResultSet
					.getString("u_anvendelighedstab")));
			horsePolicyInstance.setU_anvendelighedstab_avlshingst(Integer.parseInt(horsepolicyResultSet
					.getString("u_anvendelighedstab_avlshingst")));
			horsePolicyInstance.setU_sygeforsikring(Integer.parseInt(horsepolicyResultSet
					.getString("u_sygeforsikring")));
		} catch (Exception e) {
			System.err.println("Error message: " + e.getMessage());
			System.err.println("Error number: "
					+ ((SQLException) e).getErrorCode());
		}
		return horsePolicyInstance;
	}
	
	//fantastisk metode, den fortjener nok en oscar...
	public void printtabledata(ResultSet inputSet) {
		java.sql.ResultSetMetaData metaData;
		try {
			metaData = inputSet.getMetaData();
			int culumnN = metaData.getColumnCount();
			// Get the column names; column N starts from 1
			for (int i = 1; i < culumnN + 1; i++) {
				System.out.println(metaData.getTableName(i) + "->"
						+ metaData.getColumnName(i));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
